using System;
using System.Text;
using System.Data;
using Org.EasyWeb.Sys;
using Org.EasyWeb.Data;
using Org.EasyWeb.DataAccess;

namespace Org.EasyWeb.Right
{
	public class MobileDataRightItem : DataRightItem
	{
		public MobileDataRightItem() : base("mobile")
		{
		}

		public override void Initialize(object data)
		{
			Clear();
			BaseDataSet dataSet = new BaseDataSet() ;
			dataSet.ConnectionStr = AppSettings.Current.ConnectionString ;
			TableSelector selector = new TableSelector(dataSet) ;
			//object userID = ((IUserInfo)data).UserID ;
			using (dataSet)
			{
//				selector.SelectSql("SYS_ORGANIZATION", string.Format("SELECT ORG_ID, ORG_LAYER, ORG_PARENT_ID " + 
//					"FROM SYS_ORGANIZATION,UR_USERS WHERE USER_ORG_ID = ORG_ID AND USER_ID = '{0}'", userID)) ;
				selector.SelectSql("SYS_ORGANIZATION", string.Format("SELECT ORG_ID, ORG_LAYER, ORG_PARENT_ID " + 
					"FROM SYS_ORGANIZATION WHERE ORG_ID='{0}'", ((IUserInfo)data).RoleID)) ;
				if (dataSet.Tables.Contains("SYS_ORGANIZATION") && dataSet.Tables["SYS_ORGANIZATION"].Rows.Count > 0)
				{
					DataRow row = dataSet.Tables["SYS_ORGANIZATION"].Rows[0] ;
					string layer = row["ORG_LAYER"].ToString() ;
					StringBuilder layers = new StringBuilder() ;
					layers.AppendFormat("'{0}'", layer) ;
					for (int i=3; i<=layer.Length-3; i=i+3)
					{
						layers.AppendFormat(",'{0}'", layer.Substring(0,i)) ;
					}
					selector.SelectSql("ParentCom", string.Format("SELECT ORG_ID FROM SYS_ORGANIZATION WHERE ORG_LAYER IN ({1})", row["ORG_ID"], layers.ToString())) ;
					foreach (DataRow subRow in dataSet.Tables["ParentCom"].Rows)
					{
						ROList.Add(subRow["ORG_ID"].ToString()) ;
					}
					RWList.Add(row["ORG_ID"].ToString()) ;
				}
				InitializePublicString() ;
			}
		}

		public override string GetPublicSql(string fieldName, object userID)
		{
			return string.Format("{0} IN ({1})", fieldName, PublicString) ;
		}
	}
}
